package com.siti.kindnessplatform.click.biz;

import com.siti.kindnessplatform.click.mapper.EncourageMapper;
import com.siti.kindnessplatform.config.EasyCache;
import com.siti.kindnessplatform.util.GetIpFormRequestUtil;
import com.siti.kindnessplatform.view.biz.ViewBiz;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;


@Service
@Transactional
public class EncourageBiz {

    @Resource
    private EncourageMapper encourageMapper;

    @Resource
    EasyCache easyCache;

    public boolean encourageIt(String hospitalName, HttpServletRequest request) {
        if(hospitalName==null||"".equals(hospitalName)){
            try {
                RedissonClient redisson = easyCache.redisson;
                RAtomicLong num = redisson.getAtomicLong(ViewBiz.INDEX_LIKE_WITHOUT_NAME);
                num.incrementAndGet();
                return true;
            }catch (Exception e){
                return false;
            }
        }else {
            String ip = GetIpFormRequestUtil.getIpAddr(request);
            // ip配置
            if (ip.equals("127.0.0.1") || ip.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ip = inet.getHostAddress();
            } else if ("".equals(ip) || ip == null) {
                return false;
            }
            try {
                if (encourageMapper.insertEncourage(hospitalName, ip) > 0) {
                    int num=encourageMapper.updateHospitalById(hospitalName);
                    System.out.println("----------updateHospitalById----------"+num);
                    if (num> 0) {
                        return true;
                    }
                }
            } catch (Exception e) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }

            return false;
        }
    }


}
